<!--
 Author:lzf
 time:24/5/7
 -->
<template>
  <scroll-view :style="{height : pageHeight + 'px'}" scroll-y="true">
    <view class="content">
      <tui-loading v-if="loadingTips" :isMask="true"></tui-loading>
      <!-- 顶部卡片 -->
      <view class="planCard">
        <view class="planItem">
          <view class="itemTop">
            <view class="itemTopL">
              <view class="itemImage">
                <image :src="cardData.themeImg" mode="scaleToFill"></image>
              </view>
            </view>
            <view class="itemTopR">
              <view class="itemTitle">
                {{ cardData.name }}
              </view>
              <view class="itemTypeTag">
                {{ cardData.lineType }}
              </view>
              <view class="itemDes">
                {{ cardData.scenicCount }}个景点 | {{ cardData.taskCount }}个任务 |
                全程:{{ cardData.distance / 1000 }}KM
              </view>
            </view>
          </view>
          <view class="itemButtom">
            <view class="itemDate">
              出行日期:
              <text> {{ cardData.startTime != null ? cardData.startTime : "-" }}</text>
            </view>
            <view v-if="cardData.lineType==='拼团游'" class="memberNum">
              人数:
              <text
                  class="memberNumPing">{{ cardData.nowCount }}
              </text>
              /
              <text>{{ cardData.allCount }}</text>
            </view>
            <view v-else class="memberNum">
              人数:
              <text>{{ cardData.nowCount }}</text>
            </view>
          </view>
        </view>
      </view>
      <!-- 卡片end -->
      <!-- 旅行助手 -->
      <view class="tripAssist">
        <view class="titleTop">
          <view class="titleText">
            旅行助手
          </view>
          <view class="travelReport" @tap="toReport()">
            行程报告>
          </view>
        </view>
        <view class="menuList">
          <view class="gridWarp">
            <view v-for="(item,index) in menuList" :key="index">
              <view :style="{backgroundColor: item.bgColor}" class="menuItem"
                    @tap="handleMenu(item,index)">
                {{ item.name }}
              </view>
            </view>
          </view>
        </view>
      </view>
      <!-- 旅行助手end -->

      <!-- 轨迹图 -->
      <view class="planMapView">
        <view class="planMap">
          <map id="map" :include-points="markers" :markers="markers" :polyline="polyline"
               style="width: 100%; height: 480rpx;"></map>
        </view>
      </view>
      <!-- 轨迹图end -->

      <!-- 路线景点 -->
      <view class="attractionsWarp">
        <view v-for="(item,index) in acItemList.scenics" :key="index"
              :class="acItemList.scenicHistories[index].locked&&acItemList.scenicHistories[index].status >0? 'attractionsBorder':''"
              class="attractionsItem">
          <view class="landscapeIcon">
            <image v-if="acItemList.scenicHistories[index].locked&&acItemList.scenicHistories[index].status >0"
                   mode="aspectFit"
                   src="https://echengtuhua.oss-cn-shenzhen.aliyuncs.com/locIconSelect.png">
            </image>
            <image v-else mode="aspectFit"
                   src="https://echengtuhua.oss-cn-shenzhen.aliyuncs.com/locIcon.png">
            </image>
          </view>
          <view class="flexBox" style="max-width: 450rpx;">
            <view class="landscapeName">{{ item.name }}</view>
            <view class="location">
              <image mode="aspectFit"
                     src="https://echengtuhua.oss-cn-shenzhen.aliyuncs.com/locationPornt.png"
                     @click="openWxMap(item)"></image>
            </view>
          </view>
          <view class="landscapeDesc">
            {{ acItemList.scenicNotice[index] }}
          </view>
          <view class="landscapeImage">
            <image :src="item.img" mode="scaleToFill"></image>
          </view>

          <view class="landscapeMenu">
            <view v-if="acItemList.roles.leader || acItemList.roles.participant" class="taskBtn"
                  @tap="showSheet(index)">
              任务清单
            </view>
            <view v-if="acItemList.roles.leader || acItemList.roles.participant"
                  class="descBtn"
                  @tap="toScSpotsInt(acItemList.scenicHistories[index],acItemList.partyId,item.id,acItemList.groupId,acItemList.totalDistance,cardData.itineraryId,index,'desc')">
              景点介绍
            </view>
            <view
                v-show="acItemList.roles.leader&& acItemList.scenicHistories[index].status >0 || acItemList.roles.participant && acItemList.scenicHistories[index].status >0"
                class=" taskChallenge descBtn"
                @tap="toScSpotsInt(acItemList.scenicHistories[index],acItemList.partyId,item.id,acItemList.groupId,acItemList.totalDistance,cardData.itineraryId,index,'task')">
              任务挑战
            </view>
            <view
                v-show="acItemList.roles.leader&& acItemList.scenicHistories[index].status >0|| acItemList.roles.participant && acItemList.scenicHistories[index].status>0"
                class="taskPhoto descBtn"
                @tap="toScSpotsInt(acItemList.scenicHistories[index],acItemList.partyId,item.id,acItemList.groupId,acItemList.totalDistance,cardData.itineraryId,index,'album')">
              旅程留影
            </view>
          </view>
          <view v-if="acItemList.scenicHistories[index].status>0 &&  index + 1 < acItemList.scenicHistories.length &&
              acItemList.scenicHistories[index + 1].status === 0" class="nextlandscape" @tap="nextPlace(item,index)">
            进入下一个景点
          </view>
          <view
              v-else-if="acItemList.scenicHistories[index].status===2 &&index + 1 < acItemList.scenicHistories.length &&acItemList.scenicHistories[index+1].locked"
              class=" completeTag">
            已完成
          </view>
          <!-- 完成最后一个景点 -->
          <view v-else-if="acItemList.scenicHistories[index].status===2 && index === acItemList.scenics.length-1"
                class="completeTag">
            该路线已完成
          </view>
        </view>
      </view>
      <!-- end -->

      <!-- 任务清单弹窗 -->
      <view>
        <tui-modal :show=" isShowSheet" custom maskClosable padding="10" radius="15" @cancel="closeSheet">
          <view class="taskSheet">
            <image :src="acItemList.taskBackGround" class="SheetBg">
            </image>
            <view class="sheetTitle">任务单</view>
            <view class="taskList">
              <scroll-view scroll-y="true">
                <view class="behaviorList">
                  <text>◆行为类任务</text>
                  <view v-for="(ite,index) in acItemList.taskList[Taskindex].behaviorList"
                        :key="index" class="listItem">
                    {{ ite.name || '该景点无任务' }}
                  </view>
                </view>
                <view class="QAList">
                  <text>◆问答类任务</text>
                  <view v-for="(i,index) in acItemList.taskList[Taskindex].QAList" :key="index"
                        class="listItem">
                    {{ i.name || '该景点无任务' }}
                  </view>
                </view>
              </scroll-view>
            </view>
          </view>
        </tui-modal>
      </view>
      <!-- 加载提示 -->
      <!-- end -->
    </view>
    <zy-modal></zy-modal>
  </scroll-view>
</template>

<script>
import {
  getTravePlanDetail,
  startTraveling,
  goNextPlace
} from '@/api/tourplan.js'
import {
  judgeApperception
} from "@/api/challenge";

export default {
  data() {
    return {
      pageHeight: 750,
      userPower: {},
      loadingTips: false, //加载提示
      cardData: [], //顶部卡片数据
      proposalId: 0, //方案id
      menuList: [],

      // 地图map数据
      markers: [],
      polyline: [{
        points: [],
        color: "#2B7BBB",
        width: 5
      }],
      //end
      acItemList: [], //路线景点数据
      //任务清单
      isShowSheet: false, //弹窗显示控制
      Taskindex: 0,
    }
  },
  onLoad: function (options) {
    const that = this
    uni.getSystemInfo({
      success: function (res) {
        that.pageHeight = res.windowHeight
      }
    });

    //初始化数据
    that.initData(options)
  },
  onShow() {
    const that = this
    that.getDetail()
  },
  methods: {
    //初始化数据
    async initData(options) {
      const that = this
      that.loadingTips = true
      //接收传递的数据，将 JSON 字符串转换回对象
      that.cardData = JSON.parse(decodeURIComponent(options.planItem));
      if (that.cardData.status === 1 || that.cardData.status === 2) {
        that.menuList[4].bgColor = '#92BCFF'
      }
      //获取旅程计划详情
    },

    //获取路线详情
    getDetail() {
      const that = this
      getTravePlanDetail({
        tel: uni.getStorageSync("userinfo").phone,
        itineraryId: that.cardData.itineraryId
      }).then(async res => {
        that.acItemList = await res
        //初始化旅行助手菜单
        that.menuList = res.roleMenus
        if (res.roles.principal && res.scenicHistories[0].locked) {
          let foundItem = that.menuList.find(item => item.name === '开始旅行')
          if (foundItem) {
            foundItem.bgColor = '#92BCFF'; // 修改为目标值
          }
        }
        //初始化轨迹图
        await that.initMap(res.scenics)
        that.loadingTips = false
      }).catch(err => {
        that.loadingTips = false
        uni.showToast({
          title: err.msg,
          icon: 'none',
          duration: 3000,
        })
      })
    },

    //初始化轨迹图数据
    initMap(list) {
      const that = this
      //创建地图map对象
      let mapCtx = wx.createMapContext('map');
      //路线
      for (let i = 0; i < list.length; i++) {
        that.polyline[0].points.push({
          longitude: list[i].x,
          latitude: list[i].y
        })
        //标点
        that.markers.push({
          id: i + 1,
          longitude: list[i].x,
          latitude: list[i].y,
          width: 18,
          height: 22,
        })
        //主动触发map对象的includePoints方法
        mapCtx.includePoints({
          padding: [20, 20, 20, 20],
          points: that.markers,
        });
      }
    },

    //打开微信内置地图
    openWxMap(item) {
      const longitude = Number(item.x)
      const latitude = Number(item.y)
      wx.openLocation({
        latitude: latitude,
        longitude: longitude,
        name: String(item.name),
        scale: 18,
      })
    },

    //处理旅行助手模块按钮点击
    handleMenu(item, index) {
      switch (item.name) {
        case '开始旅行':
          this.startTravel(this.cardData.itineraryId)
          break;
        case '添加人员':
          uni.navigateTo({
            url: '/pages/tourplan/passengerInfo/passengerInfo?itineraryId=' + this
                .cardData
                .itineraryId + '&lineType=' + this.cardData.lineType
          })
          break;
        case '分组管理':
          uni.navigateTo({
            url: '/pages/tourplan/groupManage/groupManage?itineraryId=' + this
                .cardData.itineraryId
          })
          break;
        case '小组信息':
          const that = this
          if (this.acItemList.roles.leader) {
            uni.navigateTo({
              url: '/pages/tourplan/groupInfo/groupInfo?itineraryId=' + this
                      .cardData
                      .itineraryId +
                  '&scenic=' + encodeURIComponent(JSON.stringify(this.acItemList
                      .scenics)) +
                  '&groupId=' + this.acItemList.groupId + '&rolesJSON=' + encodeURIComponent(JSON
                      .stringify(this.acItemList.roles))
            })
          } else {
            uni.navigateTo({
              url: '/pages/tourplan/groupInfoTL/groupInfoTL?itineraryId=' + this
                      .cardData
                      .itineraryId +
                  '&scenic=' + encodeURIComponent(JSON.stringify(this.acItemList
                      .scenics)) +
                  '&groupId=' + this.acItemList.groupId
            })
          }
          break;
        case '集合通知':
          const rolesJSON = JSON.stringify(this.acItemList.roles);
          const url =
              `/pages/tourplan/noticeGather/noticeGather?itineraryId=${this.cardData.itineraryId}&roles=${encodeURIComponent(rolesJSON)}&groupId=${this.acItemList.groupId}&proposalId=${this.cardData.proposalId}`;
          uni.navigateTo({
            url: url
          })
          break;
        case '就餐地点':
          uni.navigateTo({
            url: '/pages/tourplan/diningPlace/diningPlace?proposalId=' + this
                .cardData
                .proposalId
          })
          break;
        case '任务管理':
          uni.navigateTo({
            url: '/pages/tourplan/taskManage/taskManage?itineraryId=' + this
                    .cardData.itineraryId +
                '&scenic=' + encodeURIComponent(JSON.stringify(this.acItemList
                    .scenics))
          })
          break;
        case '后勤信息':
          uni.navigateTo({
            url: '/pages/tourplan/logistics/logistics?itineraryId=' + this.cardData
                .itineraryId
          })
          break;
        case '旅程留影':
          uni.navigateTo({
            url: '/pages/tourplan/journeyAlbum/journeyAlbum?itineraryId=' + this
                    .cardData
                    .itineraryId + '&groupId=' + this.acItemList.groupId +
                '&partyId=' + this
                    .acItemList.partyId + '&rolesJSON=' + encodeURIComponent(JSON.stringify(this
                    .acItemList.roles))
          })
          break;
        default:
          console.log('默认')

      }
    },


    //领队开始行程
    startTravel() {
      const that = this
      if (that.cardData.status === 1 || that.cardData.status === 2) {
        uni.showToast({
          title: '当前行程已开始',
          icon: 'none',
          duration: 3000,
        })
      } else {
        startTraveling({
          itineraryId: that.cardData.itineraryId
        }).then(async (res) => {
          that.loadingTips = true
          //操作完成，更新数据
          await that.getDetail()
          that.cardData.status = 1
          uni.showToast({
            title: '旅行已开始',
            icon: 'success',
            duration: 3000,
          })
        }).catch(err => {
          that.loadingTips = false
          uni.showToast({
            title: err,
            icon: 'none',
            duration: 3000,
          })
          console.log(err)
        })
      }
    },

    //下一个景点
    nextPlace(item, index) {
      const that = this
      if (that.acItemList.scenicHistories[index].status === 1) {
        uni.showToast({
          title: '请先完成任务',
          icon: 'none',
          duration: 2000,
        })
        return
      } else if (!that.acItemList.scenicHistories[index + 1].locked) {
        uni.showToast({
          title: '请让组长上传此景点团队照片以解锁下一景点',
          icon: 'none',
          duration: 2000,
        })
        return
      }
      const navigateData = {
        partyId: that.acItemList.partyId,
        scenicId: that.acItemList.scenics[index + 1].id,
        locked: that.acItemList.scenicHistories[index + 1].locked,
        status: that.acItemList.scenicHistories[index + 1].status,
        groupId: that.acItemList.groupId,
        groupScenicId: that.acItemList.scenicHistories[index + 1].groupScenicId,
        totalDistance: that.acItemList.totalDistance,
        itineraryId: that.cardData.itineraryId,
        activeName: 'desc',
        roles: this.acItemList.roles,
        prevSenicId: item.id,
      }
      uni.setStorageSync('taskChangeTab', JSON.stringify(navigateData))
      uni.navigateTo({
        url: '/pages/tourplan/taskChallenge/taskChallenge',
      })

    },

    //获取任务索引数据，打开弹窗
    showSheet(index) {
      this.Taskindex = index
      this.isShowSheet = true
    },

    //关闭任务单弹窗
    closeSheet() {
      this.isShowSheet = false
    },

    //跳转景点介绍
    toScSpotsInt(scenicHistories, partyId, scenicId, groupId, totalDistance, itineraryId, nowIndex, activeName) {
      const that = this
      if (nowIndex === 0) {
        console.log('当前索引', nowIndex)
        const navigateData = {
          partyId: partyId,
          scenicId: scenicId,
          locked: scenicHistories.locked,
          status: scenicHistories.status,
          groupId: groupId,
          groupScenicId: scenicHistories.groupScenicId,
          totalDistance: totalDistance,
          itineraryId: itineraryId,
          activeName: activeName,
          roles: this.acItemList.roles
        }
        uni.setStorageSync('taskChangeTab', JSON.stringify(navigateData))
        uni.navigateTo({
          url: '/pages/tourplan/taskChallenge/taskChallenge',
        })
        /**
         * ?partyId=' + partyId +
         '&scenicId=' +
         scenicId + '&locked=' + scenicHistories.locked + '&status=' +
         scenicHistories.status +
         '&groupId=' + groupId + '&groupScenicId=' + scenicHistories.groupScenicId +
         '&totalDistance=' + totalDistance + '&itineraryId=' + itineraryId + '&active=' +
         activeName + '&rolesJSON=' + encodeURIComponent(JSON.stringify(this.acItemList.roles))
         **/
      } else {
        console.log('当前索引', nowIndex)
        const prevSenic = that.acItemList.scenics[nowIndex - 1]
        const navigateData = {
          partyId: partyId,
          scenicId: scenicId,
          locked: scenicHistories.locked,
          status: scenicHistories.status,
          groupId: groupId,
          groupScenicId: scenicHistories.groupScenicId,
          totalDistance: totalDistance,
          itineraryId: itineraryId,
          activeName: activeName,
          roles: this.acItemList.roles,
          prevSenicId: prevSenic.id,
        }
        uni.setStorageSync('taskChangeTab', JSON.stringify(navigateData))
        uni.navigateTo({
          url: '/pages/tourplan/taskChallenge/taskChallenge'
        })
        /**
         * ?partyId=' + partyId +
         '&scenicId=' +
         scenicId + '&locked=' + scenicHistories.locked + '&status=' +
         scenicHistories.status +
         '&groupId=' + groupId + '&groupScenicId=' + scenicHistories.groupScenicId +
         '&totalDistance=' + totalDistance + '&itineraryId=' + itineraryId + '&prevSenicId=' +
         prevSenic.id + '&active=' + activeName + '&rolesJSON=' +
         encodeURIComponent(JSON.stringify(this.acItemList.roles))
         **/
      }

    },

    //跳转行程报告
    toReport() {
      judgeApperception({
        partyId: this.acItemList.partyId
      }).then(res => {
        console.log('输出res', res);
        if (res == true) {
          uni.navigateTo({
            url: '/pages/tourplan/travelReport/travelReport?itineraryId=' + this.cardData
                    .itineraryId +
                '&partyId=' + this.acItemList.partyId + '&groupId=' + this.acItemList
                    .groupId +
                '&returnType=1&deltaNumber=1'
          })
        } else {
          uni.navigateTo({
            url: '/pages/challenge/tripPerception?itineraryId=' + this.cardData
                    .itineraryId + '&partyId=' + this.acItemList.partyId + '&groupId=' + this
                    .acItemList.groupId +
                '&returnType=1&deltaNumber=1'
          })

        }
      })
    },

  }
}
</script>

<style>
@import url("planDetail.css");
</style>
